#!/usr/bin/env node

const readline = require('readline');
const { calculateEntropy, parseArguments, validateProbabilities } = require('./entropy');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const args = process.argv.slice(2);

try {
  if (args.length === 0) {
    throw new Error('无命令行参数');
  }
  const input = args.join(',');
  const probabilities = parseArguments(input);
  if (!validateProbabilities(probabilities)) {
    throw new Error('概率空间不封闭，概率和不等于1！');
  }
  const entropy = calculateEntropy(probabilities);
  console.log(`p = [${probabilities}]\nh(p) = ${entropy.toFixed(3)} bit`);
} catch (error) {
  console.error(error.message + '\n');
  rl.question('请输入信源概率分布：（ctrl+D 退出输入）\n', input => {
    try {
      const probabilities = parseArguments(input);
      if (!validateProbabilities(probabilities)) {
        throw new Error('概率空间不封闭，概率和不等于1！');
      }
      const entropy = calculateEntropy(probabilities);
      console.log(`p = [${probabilities}]\nh(p) = ${entropy.toFixed(3)} bit`);
    } catch (error) {
      console.error('错误：' + error.message);
    }
    rl.close();
  });
}